/*
 * DataFactory.java
 *
 * Created on July 16, 2007, 23:09:12
 */

package net.siit.util;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;

/**
 *
 * @author arthit
 */
public class DataFactory {
    
    public DataFactory() {
    }
    
    
    /**
     * 
     * @param dictionaryURL 
     * @param dictionaryEncoding 
     * @param valuer 
     * @return a trie that contains words in dictionaryURL
     * @throws java.net.URISyntaxException 
     * @throws java.io.UnsupportedEncodingException 
     * @throws java.io.FileNotFoundException 
     * @throws java.io.IOException 
     */
    public static org.speedblue.util.Trie createTrieDictionary(URL dictionaryURL, String dictionaryEncoding, Valuer valuer)
            throws URISyntaxException, UnsupportedEncodingException, FileNotFoundException, IOException {
        org.speedblue.util.Trie dict = new org.speedblue.util.Trie(1000);
        
        BufferedReader dictReader = null;
        dictReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(dictionaryURL.toURI())), dictionaryEncoding));
        
        String line = null;
        while ((line = dictReader.readLine()) != null) {
            try {
                dict.addEntry(line, valuer.valueOf(line));
            } catch(Exception ex) {
                // Exception thrown when duplicated entry is being added - just ignore
            }
        }
        
        dictReader.close();
        
        return dict;
    }

    /**
     * 
     * @param dictionaryURL 
     * @param dictionaryEncoding 
     * @return a trie that contains words in dictionaryURL
     * @throws java.net.URISyntaxException 
     * @throws java.io.UnsupportedEncodingException 
     * @throws java.io.FileNotFoundException 
     * @throws java.io.IOException 
     */
    public static org.speedblue.util.Trie createTrieDictionary(URL dictionaryURL, String dictionaryEncoding)
            throws URISyntaxException, UnsupportedEncodingException, FileNotFoundException, IOException {
        return createTrieDictionary(dictionaryURL, dictionaryEncoding, new DefaultValuer());
    }

    public interface Valuer {
        public int valueOf(String str);
    }
    
    public static class DefaultValuer implements Valuer {

        /**
         * Value of String
         * This method will always return 1.
         * @param str String
         * @return 1
         */
        @Override
        public int valueOf(String str) {
            return 1;
        }
    }
    
    public static class LengthValuer implements Valuer {

        /**
         * Value of String
         * @param str String
         * @return length of str; -1 if str is null.
         */
        @Override
        public int valueOf(String str) {
            if (str == null)
                return -1;
            return str.length();
        } 
    }
}
